package cn.dakaqi.activity.services;

import cn.dakaqi.api.qnzyz.activity.BHActivityService;
import cn.dakaqi.entities.*;
import cn.dakaqi.group.services.GroupService;
import cn.dakaqi.log.services.LogService;
import cn.dakaqi.member.service.VolunteerService;
import cn.dakaqi.utils.BaseDAO;
import cn.dakaqi.utils.DKQConstant;
import cn.dakaqi.utils.DateUtil;
import cn.dakaqi.utils.Identities;
import cn.dakaqi.utils.exception.ServiceRuntimeException;
import cn.dakaqi.utils.qrcode.ImageType;
import cn.dakaqi.utils.qrcode.QRCode;
import cn.dakaqi.utils.rongYun.PushActivityMesssage;
import cn.dakaqi.utils.rongYun.PushGroupMesssage;
import cn.dakaqi.utils.rongYun.PushSystemMesssage;
import cn.dakaqi.volunteer.tag.PlatformGroup2Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.utils.Clock;

import java.io.ByteArrayOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by chunyang on 2016/4/14.
 */
// Spring Bean的标识.
@Component(value = "activityService")
// 类中所有public函数都纳入事务管理的标识.
@Transactional
public class ActivityServiceImpl implements ActivityService
{
    @Autowired
    ActivityDao activityDao;
    @Autowired
    VolunteerService volunteerService;
    @Autowired
    GroupService groupService;
    @Autowired
    BHActivityService bhActivityService;
    @Autowired
    BaseDAO baseDAO;
    @Autowired
    PlatformGroup2Service platformGroup2Service;
    @Autowired
    private LogService logService;

    private void saveLog(String message)
    {
        logService.save(200,message);
    }
    @Override
    public List<Activity> save(String json) throws ServiceRuntimeException
    {
        JSONObject jsonObject = JSON.parseObject(json);

        String province = jsonObject.getString("province");            //活动名称
        String city = jsonObject.getString("city");            //活动名称
        String district = jsonObject.getString("district");            //活动名称
        String lng = jsonObject.getString("lng");            //活动名称
        String lat = jsonObject.getString("lat");            //活动名称
        String name = jsonObject.getString("name");            //活动名称
        String demo= jsonObject.getString("demo");            //活动简单
        String imgs= jsonObject.getString("imgs");            //图片
        String startTime= jsonObject.getString("startTime");       //开始日期
        String endTime= jsonObject.getString("endTime");         //结束日期
        int type= jsonObject.getIntValue("type");               //活动开展类型
        String address= jsonObject.getString("address");         //活动地址
        String tags= jsonObject.getString("tags");            //标签
        String skill= jsonObject.getString("skill");            //标签
        String weekDay= jsonObject.getString("weekDay");         //周期
        int needs= jsonObject.getIntValue("needs");              //所需人数
        int scope= jsonObject.getIntValue("scope");              //签到误差范围
        String monitorMemberCode= jsonObject.getString("monitorMemberCode");      //现场负责人
        String crateUseMemberCode= jsonObject.getString("crateUseMemberCode");    //活动发布者
        String groupCode= jsonObject.getString("groupCode");            //所属组织

        //检查活动时间最长一个月
        long days = DateUtil.countDay(startTime,endTime);
        if(days>31)
            throw new ServiceRuntimeException("只能发最近一个月的周期性活动。");

        Activity activity = new Activity();
        Volunteer volunteerCreateUser = null;
        Volunteer volunteerMonitor = volunteerService.findByMemberCode(monitorMemberCode);
        if(!monitorMemberCode.equals(crateUseMemberCode))
            volunteerCreateUser = volunteerService.findByMemberCode(crateUseMemberCode);
        else
            volunteerCreateUser = volunteerMonitor;

//        if(StringUtils.isBlank(volunteerCreateUser.getVolunteerCode()))
//            throw new ServiceRuntimeException("请完成实名认证");

        Group group = this.groupService.findByGroupCode(groupCode);

        activity.setGroup(group);
        activity.setCreateUser(volunteerCreateUser);
        activity.setMonitor(volunteerMonitor);
        activity.setSkill(skill);
        activity.setScope(scope);
        activity.setNeeds(needs);
        activity.setName(name);
        activity.setDemo(demo);
        activity.setImgs(imgs);
        activity.setType(type);
        activity.setStartTime(startTime);
        activity.setEndTime(endTime);
        activity.setAddress(address);
        activity.setTags(tags);
        activity.setWeekDay(weekDay);
        activity.setProvince(province);
        activity.setCity(city);
        activity.setDistrict(district);
        activity.setLng(Double.valueOf(lng));
        activity.setLat(Double.valueOf(lat));
        List<Activity> activityList = this.save(activity);

        return activityList;
    }

    public static void main(String[] args)
    {

        try
        {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            SimpleDateFormat chineseFormatter = new SimpleDateFormat("MM月dd日");
            System.out.println(chineseFormatter.format(sdf.parse("2016-06-15 14:20")) + " tttttt ");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }
    @Override
    public List<Activity> save(Activity activity) throws ServiceRuntimeException
    {
        activity.setCreateTime(Clock.DEFAULT.getCurrentDate());
        activity.setSelfGroup(0);
        activity.setApplys(0);
        activity.setTimes(0);
        String address = activity.getAddress().replace(activity.getProvince(),"");
        address = address.replace(activity.getCity(),"");
        address = address.replace(activity.getDistrict(),"");
        if(activity.getProvince().equals(activity.getCity()))
            address = activity.getProvince()+activity.getDistrict()+address;
        else
            address = activity.getProvince()+activity.getCity()+activity.getDistrict()+address;
        activity.setAddress(address);

        List<Activity> activityList = new ArrayList<Activity>();
        if(activity.getType() == Activity.TYPE_3)
        {
            //周期活动
            //连续多天活动
            String startDay = activity.getStartTime().split(" ")[0];
            String startTime = activity.getStartTime().split(" ")[1];
            String endDay = activity.getEndTime().split(" ")[0];
            String endTime = activity.getEndTime().split(" ")[1];

            List<String> list = DateUtil.getEveryday(startDay, endDay);
            List<Activity> activities = new ArrayList<Activity>();

            SimpleDateFormat DefaultDateFormatter = new SimpleDateFormat("yyyy-MM-dd");
            for(String str:list)
            {
                try
                {
                    //判断当前日期是星期几
                    int week = DateUtil.week(DefaultDateFormatter.parse(str));
                    if(activity.getWeekDay().contains(String.valueOf(week)))
                    {
                        Activity tempAct = new Activity();
                        activity.setStartTime(str + " " + startTime);
                        activity.setEndTime(str + " " + endTime);
                        activity = constructionActivity(activity);
                        BeanUtils.copyProperties(activity,tempAct);
                        activities.add(tempAct);
                    }

                } catch (ParseException e)
                {
                    e.printStackTrace();
                }

            }
            if(activities.size()>0)
            {
                for (Activity act : activities)
                {
                    try
                    {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        SimpleDateFormat chineseFormatter = new SimpleDateFormat("MM月dd日");
                        act.setName(chineseFormatter.format(sdf.parse(act.getStartTime())) + " " + act.getName());
                    } catch (ParseException e)
                    {
                        e.printStackTrace();
                    }
                    act  = this.activityDao.save(act);
                    saveLog("用户【"+act.getCreateUser().getId()+"】发布了一个活动【"+act.getId()+"】"+act.getName());
                    activityList.add(act);
                    submit2BH(act);
                }
                //更新社团活动数量
                Group group = activity.getGroup();
                group.setActvitys(group.getActvitys()+activities.size());
                this.groupService.update(group);
                //活动的发布者 现场联系上自动报名参加当前活动，并是活动管理员
                for(Activity act:activities)
                {
                    //活动的发布者
                    //this.activityDao.applyActivity(Clock.DEFAULT.getCurrentDate(),DKQConstant.ROLES_ADMIN,DKQConstant.APPLY_STATUS_OK,act.getId(),act.getCreateUser().getId());
                    //活动的现场联系人
                    //if(act.getCreateUser().getId() != act.getMonitor().getId())
                    {
                        this.activityDao.applyActivity(Clock.DEFAULT.getCurrentDate(), DKQConstant.ROLES_ADMIN, DKQConstant.APPLY_STATUS_OK, act.getId(), act.getMonitor().getId());
                        PushActivityMesssage.getInstance().setActivityMonitor(activity.getName(),activity.getMonitor().getMemberCode(),activity.getActivityCode());
                        //向社团成员发消息
                        PushGroupMesssage.getInstance().createNewActivity(baseDAO,act.getActivityCode(),act.getName(),act.getGroup().getId(),act.getGroup().getName());
                    }
                }
            }

        }
        else if(activity.getType() == Activity.TYPE_2)
        {
            //连续多天活动
            String startDay = activity.getStartTime().split(" ")[0];
            String startTime = activity.getStartTime().split(" ")[1];
            String endDay = activity.getEndTime().split(" ")[0];
            String endTime = activity.getEndTime().split(" ")[1];

            List<String> list = DateUtil.getEveryday(startDay, endDay);
            List<Activity> activities = new ArrayList<Activity>();


            for(String str:list)
            {
                Activity tempAct = new Activity();
                activity.setStartTime(str + " " + startTime);
                activity.setEndTime(str + " " + endTime);
                activity = constructionActivity(activity);
                BeanUtils.copyProperties(activity,tempAct);
                activities.add(tempAct);
            }
            if(activities.size()>0)
            {
                for(Activity act:activities)
                {
                    try
                    {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        SimpleDateFormat chineseFormatter = new SimpleDateFormat("MM月dd日");
                        act.setName(chineseFormatter.format(sdf.parse(act.getStartTime())) + " " + act.getName());
                    } catch (ParseException e)
                    {
                        e.printStackTrace();
                    }
                    act = this.activityDao.save(act);
                    activityList.add(act);
                    saveLog("用户【"+act.getCreateUser().getId()+"】发布了一个活动【"+act.getId()+"】"+act.getName());
                    submit2BH(act);
                }

                //更新社团活动数量
                Group group = activity.getGroup();
                group.setActvitys(group.getActvitys()+activities.size());
                this.groupService.update(group);
                //活动的发布者 现场联系上自动报名参加当前活动，并是活动管理员
                for(Activity act:activities)
                {
                    //活动的发布者
                    //this.activityDao.applyActivity(Clock.DEFAULT.getCurrentDate(),DKQConstant.ROLES_ADMIN,DKQConstant.APPLY_STATUS_OK,act.getId(),act.getCreateUser().getId());
                    //活动的现场联系人
                    //if(act.getCreateUser().getId() != act.getMonitor().getId())
                    {
                        this.activityDao.applyActivity(Clock.DEFAULT.getCurrentDate(),DKQConstant.ROLES_ADMIN,DKQConstant.APPLY_STATUS_OK,act.getId(),act.getMonitor().getId());
                        PushActivityMesssage.getInstance().setActivityMonitor(activity.getName(),activity.getMonitor().getMemberCode(),activity.getActivityCode());
                        //向社团成员发消息
                        PushGroupMesssage.getInstance().createNewActivity(baseDAO,act.getActivityCode(),act.getName(),act.getGroup().getId(),act.getGroup().getName());
                    }
                }
            }

        }
        else
        {
            constructionActivity(activity);
            activity = this.activityDao.save(activity);
            saveLog("用户【"+activity.getCreateUser().getId()+"】发布了一个活动【"+activity.getId()+"】"+activity.getName());
            activityList.add(activity);

            //向北航提交活动数据
            submit2BH(activity);

            //更新社团活动数量
            Group group = activity.getGroup();
            group.setActvitys(group.getActvitys()+1);
            this.groupService.update(group);
            //活动的发布者 现场联系上自动报名参加当前活动，并是活动管理员

            //活动的发布者
            //this.activityDao.applyActivity(Clock.DEFAULT.getCurrentDate(),DKQConstant.ROLES_ADMIN,DKQConstant.APPLY_STATUS_OK,activity.getId(),activity.getCreateUser().getId());
            //活动的现场联系人
            //if(activity.getCreateUser().getId() != activity.getMonitor().getId())
            {
                this.activityDao.applyActivity(Clock.DEFAULT.getCurrentDate(),DKQConstant.ROLES_ADMIN,DKQConstant.APPLY_STATUS_OK,activity.getId(),activity.getMonitor().getId());
                //System.out.println(activity.getName() + "--------1------->" + activity.getMonitor().getMemberCode()+"-------------->" + activity.getActivityCode());
                PushActivityMesssage.getInstance().setActivityMonitor(activity.getName(),activity.getMonitor().getMemberCode(),activity.getActivityCode());
            }
            //向社团成员发消息
            PushGroupMesssage.getInstance().createNewActivity(baseDAO,activity.getActivityCode(),activity.getName(),activity.getGroup().getId(),activity.getGroup().getName());
        }

        return activityList;

    }

    /**
     * 向北航提交活动数据
     * @param activity
     * @return
     */
    private Activity submit2BH(Activity activity)
    {
        //北航注册活动
        if(StringUtils.isNotBlank(activity.getGroup().getGroupCode()))
        {
            try
            {
                String activityCode = bhActivityService.post(activity);
                if (StringUtils.isEmpty(activityCode))
                    throw new Exception("团中央保存活动信息出错");
                activity.setActivityCode(activityCode);
            } catch (Exception e)
            {
                e.printStackTrace();
                try
                {
                    throw e;
                } catch (Exception e1)
                {
                    e1.printStackTrace();
                }
            }
        }
        List<String > userIds = new ArrayList<String>();
        userIds.add(activity.getCreateUser().getMemberCode());
        userIds.add(activity.getMonitor().getMemberCode());
        PushGroupMesssage.getInstance().createGroup(PushGroupMesssage.GROUP_TYPE_ACTIVITY,userIds,activity.getActivityCode(),activity.getName());
        return activity;
    }
    /**
     * 重新构造活动对象
     * @param activity
     * @return
     */
    private Activity constructionActivity(Activity activity)
    {
        String address = activity.getAddress();
        String p = "",c = "",d = "";
        if(!address.contains(activity.getProvince()))
            p = activity.getProvince();
        if(!address.contains(activity.getCity()))
            c = activity.getCity();
        if(!address.contains(activity.getDistrict()))
            d = activity.getDistrict();
        activity.setAddress(p+c+d+address);
//        if(activity.getCreateUser().getId() != activity.getMonitor().getId())
//            activity.setApplys(2);
//        else
            activity.setApplys(1);
        activity.setActivityCode(this.createActivityCodeForDate(activity.getProvince(),DateUtil.currentDateStringTrim()));
        //activity.setActivityCode(this.createActivityCode(activity.getProvince(), "", ""));

        //将当前的活动标识为当前社团所挂靠平台的编号
        String platform = "";
        List<PlatformGroup> list = platformGroup2Service.findByGroup(activity.getGroup().getId());
        if(null != list && list.size()>0)
        {
            for(PlatformGroup pg:list)
            {
                if(StringUtils.isNotBlank(pg.getCode()) && !"null".equals(pg.getCode()))
                    platform = platform + pg.getCode() + ";";
            }
        }
        activity.setPlatform(platform);

        return activity;
    }

    @Override
    public void update(String json) throws ServiceRuntimeException
    {
        JSONObject jsonObject = JSON.parseObject(json);
        String province = jsonObject.getString("province");            //活动名称
        String city = jsonObject.getString("city");            //活动名称
        String district = jsonObject.getString("district");            //活动名称
        String lng = jsonObject.getString("lng");            //活动名称
        String lat = jsonObject.getString("lat");            //活动名称
        String name = jsonObject.getString("name");            //活动名称
        String demo= jsonObject.getString("demo");            //活动简单
        String imgs= jsonObject.getString("imgs");            //图片
        String startTime= jsonObject.getString("startTime");       //开始日期
        String endTime= jsonObject.getString("endTime");         //结束日期
        int type= jsonObject.getIntValue("type");               //活动开展类型
        String address= jsonObject.getString("address");         //活动地址
        String tags= jsonObject.getString("tags");            //标签
        String skill= jsonObject.getString("skill");            //标签
        String weekDay= jsonObject.getString("weekDay");         //周期
        int needs= jsonObject.getIntValue("needs");              //所需人数
        int scope= jsonObject.getIntValue("scope");              //签到误差范围
        String monitorMemberCode= jsonObject.getString("monitorMemberCode");      //现场负责人
        String crateUseMemberCode= jsonObject.getString("crateUseMemberCode");    //活动发布者
        String groupCode= jsonObject.getString("groupCode");            //所属组织
        String activityCode= jsonObject.getString("activityCode");            //所属组织

        Activity activity = this.activityDao.findByActivityCode(activityCode);
        if(!activity.getMonitor().getMemberCode().equals(monitorMemberCode))
        {
            Volunteer volunteerCreateUser = null;
            Volunteer volunteerMonitor = volunteerService.findByMemberCode(monitorMemberCode);
            if (!monitorMemberCode.equals(crateUseMemberCode))
                volunteerCreateUser = volunteerService.findByMemberCode(crateUseMemberCode);
            else
                volunteerCreateUser = volunteerMonitor;

            activity.setCreateUser(volunteerCreateUser);
            activity.setMonitor(volunteerMonitor);
            this.activityDao.applyActivity(Clock.DEFAULT.getCurrentDate(), DKQConstant.ROLES_ADMIN, DKQConstant.APPLY_STATUS_OK, activity.getId(), activity.getMonitor().getId());
        }
        Group group = this.groupService.findByGroupCode(groupCode);

        activity.setSkill(skill);
        activity.setGroup(group);

        activity.setCreateTime(Clock.DEFAULT.getCurrentDate());
        activity.setScope(scope);
        activity.setNeeds(needs);
        activity.setName(name);
        activity.setDemo(demo);
        activity.setImgs(imgs);
        activity.setType(type);
        activity.setStartTime(startTime);
        activity.setEndTime(endTime);
        activity.setAddress(address);
        activity.setTags(tags);
        activity.setWeekDay(weekDay);
        activity.setSelfGroup(0);
        activity.setTimes(0L);
        activity.setProvince(province);
        activity.setCity(city);
        activity.setDistrict(district);
        activity.setLng(Double.valueOf(lng));
        activity.setLat(Double.valueOf(lat));

        address = address.replace(activity.getProvince(),"");
        address = address.replace(activity.getCity(),"");
        address = address.replace(activity.getDistrict(),"");

        if(activity.getProvince().equals(activity.getCity()))
            address = activity.getProvince()+activity.getDistrict()+address;
        else
            address = activity.getProvince()+activity.getCity()+activity.getDistrict()+address;

        activity.setAddress(address);

        this.updateActivityInfo(activity);
    }

    @Override
    public void update(Activity activity) throws ServiceRuntimeException
    {
        this.activityDao.save(activity);
        saveLog("用户【"+activity.getCreateUser().getId()+"】修改了活动【"+activity.getId()+"】"+activity.getName());
    }

    @Override
    public void updateActivityInfo(Activity activity) throws ServiceRuntimeException
    {
        this.activityDao.save(activity);
        saveLog("用户【"+activity.getCreateUser().getId()+"】修改了活动【"+activity.getId()+"】"+activity.getName());
        PushActivityMesssage.getInstance().setActivityMonitor(activity.getName(),activity.getMonitor().getMemberCode(),activity.getActivityCode());
        //向社团成员发消息
        PushGroupMesssage.getInstance().createNewActivity(baseDAO,activity.getActivityCode(),activity.getName(),activity.getGroup().getId(),activity.getGroup().getName());
        PushGroupMesssage.getInstance().updateActivity(baseDAO,activity.getActivityCode(),activity.getName(),activity.getCreateUser().getRealName(),activity.getId());
    }
    @Override
    public void delete(String param) throws ServiceRuntimeException
    {
        JSONObject jsonObject = JSON.parseObject(param);
        String memberCode = jsonObject.getString("memberCode");
        String activityCode = jsonObject.getString("activityCode");
        this.delete(memberCode,activityCode);
    }

    @Override
    public void delete(String memberCode,Long id) throws ServiceRuntimeException
    {
        Activity activity = this.findOne(id);
        if(null != activity)
        {
            if(!activity.getCreateUser().getMemberCode().equals(memberCode))
                throw new ServiceRuntimeException("只有当前活动的创建者才可以删除当前活动");
            activity.setDelStatus(DKQConstant.DEL_YES);
            this.activityDao.save(activity);
            saveLog("用户【"+activity.getCreateUser().getId()+"】删除了一个活动【"+activity.getId()+"】"+activity.getName());
            PushSystemMesssage.getInstance().delActivity(baseDAO,activity.getId(), activity.getName(), activity.getMonitor().getRealName());

            //查询活动的所有报名记录

            //查询活动的所有打卡记录

            //查询活动的所有公益记录

//            //推送消息至志愿者用户
//            List<String> volunteers = new ArrayList<String>();
//            String sql = "SELECT MEMBER_CODE FROM U_VOLUNTEER AS A INNER JOIN (SELECT VOLUNTEER_ID FROM U_ACTIVITY_SIGN WHERE ACTIVITY_ID = " + activity.getId() + " AND DEL_STATUS = "  +DKQConstant.DEL_NO + ") AS B ON B.VOLUNTEER_ID = A.ID";
//            List<Map<String,String>> list = baseDAO.queryNativeSql(sql);
//            if(null != list && list.size()>0)
//            {
//                for(Map<String,String> map:list)
//                    volunteers.add(map.get("MEMBER_CODE"));
//            }
//            PushMessageUtil.publishSystemMessage(activity.getCreateUser().getRealName()+"取消了"+activity.getName()+"活动", null, PushMessageUtil.SYSTEM_HELPER, volunteers);

        }
    }

    @Override
    public void delete(String memberCode,String activityCode) throws ServiceRuntimeException
    {
        Activity activity = this.findByActivityCode(activityCode);
        if(null == activity)
            throw new ServiceRuntimeException("指定的活动不存在");
        this.delete(memberCode,activity.getId());
    }

    @Override
    public Activity findOne(Long id) throws ServiceRuntimeException
    {
        Activity activity = this.activityDao.findOne(id);
        activity.setBrowses(activity.getBrowses()+1);
        this.activityDao.save(activity);
        return activity;
    }

    @Override
    public Activity findByActivityCode(String activityCode) throws ServiceRuntimeException
    {
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("activityCode", new SearchFilter("activityCode", SearchFilter.Operator.EQ, activityCode));
        filters.put("delStatus", new SearchFilter("delStatus", SearchFilter.Operator.EQ, DKQConstant.DEL_NO));
        Specification<Activity> spec = DynamicSpecifications.bySearchFilter(filters.values(), Activity.class);


        List<Activity> list = this.activityDao.findAll(spec);
        if(null == list || list.size() ==0)
            throw new ServiceRuntimeException("活动不存在");
        Activity activity = list.get(0);
        //activity.setBrowses(activity.getBrowses()+1);
        //this.activityDao.save(activity);
        return activity;
    }

    @Override
    public Activity findByActivityCode(String memberCode, String activityCode) throws ServiceRuntimeException
    {
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("activityCode", new SearchFilter("activityCode", SearchFilter.Operator.EQ, activityCode));
        filters.put("delStatus", new SearchFilter("delStatus", SearchFilter.Operator.EQ, DKQConstant.DEL_NO));
        Specification<Activity> spec = DynamicSpecifications.bySearchFilter(filters.values(), Activity.class);


        List<Activity> list = this.activityDao.findAll(spec);
        if(null == list || list.size() ==0)
            throw new ServiceRuntimeException("活动不存在");

        Activity activity = list.get(0);

        if(StringUtils.isNotBlank(memberCode) && !"null".equals(memberCode))
        {
            activity.setBrowses(activity.getBrowses()+1);
            this.activityDao.save(activity);
        }

        return activity;
    }

    @Override
    public Activity activityManager(String activityCode) throws ServiceRuntimeException
    {
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("activityCode", new SearchFilter("activityCode", SearchFilter.Operator.EQ, activityCode));
        filters.put("delStatus", new SearchFilter("delStatus", SearchFilter.Operator.EQ, DKQConstant.DEL_NO));
        Specification<Activity> spec = DynamicSpecifications.bySearchFilter(filters.values(), Activity.class);


        List<Activity> list = this.activityDao.findAll(spec);
        if(null == list || list.size() ==0)
            throw new ServiceRuntimeException("活动不存在");
        Activity activity = list.get(0);
        return activity;
    }

    @Override
    public Page<Activity> findByName(String name, int pageNumber) throws ServiceRuntimeException
    {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = new PageRequest(pageNumber - 1, 20, sort);

        Map<String,Object> map = new HashMap<String, Object>();
        //map.put("LIKE_NAME",name);
        //Map<String, SearchFilter> filters = SearchFilter.parse(map);

        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("name", new SearchFilter("name", SearchFilter.Operator.LIKE, name));
        filters.put("delStatus", new SearchFilter("delStatus", SearchFilter.Operator.EQ, DKQConstant.DEL_NO));
        Specification<Activity> spec = DynamicSpecifications.bySearchFilter(filters.values(), Activity.class);


        return this.activityDao.findAll(spec, pageRequest);
    }

    @Override
    public Page<Activity> findByCreateUser(Long volunteerId, int pageNumber) throws ServiceRuntimeException
    {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = new PageRequest(pageNumber - 1, 20, sort);

        Map<String,Object> map = new HashMap<String, Object>();
        //map.put("LIKE_NAME",name);
        //Map<String, SearchFilter> filters = SearchFilter.parse(map);

        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("delStatus", new SearchFilter("delStatus", SearchFilter.Operator.EQ, DKQConstant.DEL_NO));
        filters.put("createUser.id", new SearchFilter("createUser.id", SearchFilter.Operator.EQ, volunteerId));
        Specification<Activity> spec = DynamicSpecifications.bySearchFilter(filters.values(), Activity.class);


        return this.activityDao.findAll(spec, pageRequest);
    }

    @Override
    public Page<Activity> findByGroup(Long groupId, int pageNumber) throws ServiceRuntimeException
    {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = new PageRequest(pageNumber - 1, 20, sort);

        Map<String,Object> map = new HashMap<String, Object>();
        //map.put("LIKE_NAME",name);
        //Map<String, SearchFilter> filters = SearchFilter.parse(map);

        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("delStatus", new SearchFilter("delStatus", SearchFilter.Operator.EQ, DKQConstant.DEL_NO));
        filters.put("group.id", new SearchFilter("group.id", SearchFilter.Operator.EQ, groupId));
        Specification<Activity> spec = DynamicSpecifications.bySearchFilter(filters.values(), Activity.class);
        return this.activityDao.findAll(spec, pageRequest);
    }

    @Override
    public Page<Activity> findByGroupCode(String groupCode, int pageNumber) throws ServiceRuntimeException
    {
        Sort sort = new Sort(Sort.Direction.DESC, "startTime");
        PageRequest pageRequest = new PageRequest(pageNumber - 1, 20, sort);

        Map<String,Object> map = new HashMap<String, Object>();
        //map.put("LIKE_NAME",name);
        //Map<String, SearchFilter> filters = SearchFilter.parse(map);

        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("delStatus", new SearchFilter("delStatus", SearchFilter.Operator.EQ, DKQConstant.DEL_NO));
        filters.put("group.groupCode", new SearchFilter("group.groupCode", SearchFilter.Operator.EQ, groupCode));
        Specification<Activity> spec = DynamicSpecifications.bySearchFilter(filters.values(), Activity.class);
        return this.activityDao.findAll(spec, pageRequest);
    }

    @Override
    public Page<Activity> findTodayNotEnd(String today,int pageNumber) throws ServiceRuntimeException
    {
        Sort sort = new Sort(Sort.Direction.ASC, "startTime");
        PageRequest pageRequest = new PageRequest(pageNumber - 1, 1000, sort);
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("delStatus", new SearchFilter("delStatus", SearchFilter.Operator.EQ, DKQConstant.DEL_NO));
        filters.put("status", new SearchFilter("status", SearchFilter.Operator.LT, DKQConstant.PROCEED_END));
        filters.put("startTime", new SearchFilter("startTime", SearchFilter.Operator.LIKE, today));
        Specification<Activity> spec = DynamicSpecifications.bySearchFilter(filters.values(), Activity.class);
        return this.activityDao.findAll(spec, pageRequest);
    }

    @Override
    public List<Activity> findToday(String today, int status) throws ServiceRuntimeException
    {
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("delStatus", new SearchFilter("delStatus", SearchFilter.Operator.EQ, DKQConstant.DEL_NO));
        filters.put("status", new SearchFilter("status", SearchFilter.Operator.EQ, status));
        filters.put("startTime", new SearchFilter("startTime", SearchFilter.Operator.LIKE, today));
        Specification<Activity> spec = DynamicSpecifications.bySearchFilter(filters.values(), Activity.class);
        return this.activityDao.findAll(spec);
    }

    @Override
    public Page<Activity> findNotEnd(int pageNumber) throws ServiceRuntimeException
    {
        Sort sort = new Sort(Sort.Direction.ASC, "startTime");
        PageRequest pageRequest = new PageRequest(pageNumber - 1, 1000, sort);
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("delStatus", new SearchFilter("delStatus", SearchFilter.Operator.EQ, DKQConstant.DEL_NO));
        filters.put("status", new SearchFilter("status", SearchFilter.Operator.LT, DKQConstant.PROCEED_END));
        Specification<Activity> spec = DynamicSpecifications.bySearchFilter(filters.values(), Activity.class);
        return this.activityDao.findAll(spec, pageRequest);
    }

    @Override
    public Page<Activity> findEndAndUnLocked(int pageNumber) throws ServiceRuntimeException
    {
        Sort sort = new Sort(Sort.Direction.ASC, "startTime");
        PageRequest pageRequest = new PageRequest(pageNumber - 1, 1000, sort);

        Map<String,Object> map = new HashMap<String, Object>();
        //map.put("LIKE_NAME",name);
        //Map<String, SearchFilter> filters = SearchFilter.parse(map);

        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("delStatus", new SearchFilter("delStatus", SearchFilter.Operator.EQ, DKQConstant.DEL_NO));
        filters.put("status", new SearchFilter("status", SearchFilter.Operator.EQ, DKQConstant.PROCEED_END));
        filters.put("locked", new SearchFilter("locked", SearchFilter.Operator.EQ, DKQConstant.USER_UNLOCK));
        Specification<Activity> spec = DynamicSpecifications.bySearchFilter(filters.values(), Activity.class);
        return this.activityDao.findAll(spec, pageRequest);
    }

    @Override
    public void locked() throws ServiceRuntimeException
{
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    Page<Activity> data = findEndAndUnLocked(1);
    try
    {
        if(null != data && null != data.getContent() && data.getContent().size()>0)
        {
            for(Activity act:data.getContent())
            {
                Calendar calendar = Calendar.getInstance();
                String endtday = act.getEndTime();
                String nowday = sdf.format(calendar.getTime());
                //long days = DateUtil.countDay(endtday, nowday, sdf);
                int minutes = DateUtil.countMinutes(endtday,nowday);
                if(minutes >= 4*60)
                {
                    act.setLocked(DKQConstant.USER_LOCK);
                    this.activityDao.save(act);
                    List<String> volunteers = new ArrayList<String>();
                    if(act.getCreateUser().getId() == act.getMonitor().getId())
                    {
                        volunteers.add(act.getCreateUser().getMemberCode());
                    }
                    else
                    {
                        volunteers.add(act.getCreateUser().getMemberCode());
                        volunteers.add(act.getMonitor().getMemberCode());

                    }
                    PushActivityMesssage.getInstance().locked(act.getName(), volunteers);
                }
            }
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

    @Override
    public void updateStatus() throws ServiceRuntimeException
    {
//        SimpleDateFormat DefaultTimeFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        Page<Activity> data = findTodayNotEnd(DateUtil.convertDefaultDateString(new Date()), 1);
//        if(null != data && null != data.getContent() && data.getContent().size()>0)
//        {
//            for(Activity act:data.getContent())
//            {
//                if(act.getStatus() == DKQConstant.PROCEED_NOT_START)
//                {
//                    try
//                    {
//                        Date today = new Date();
//                        Date actStartDate = DefaultTimeFormatter.parse(act.getStartTime());
//                        Date actEndDate = DefaultTimeFormatter.parse(act.getEndTime());
//                        //检查当前活动是否开始
//                        if(today.after(actStartDate))
//                        {
//                            act.setStatus(DKQConstant.PROCEED_START);
//                            activityDao.save(act);
//                        }
//                        //检查当前活动是否已结束
//                        if(today.after(actEndDate))
//                        {
//                            act.setStatus(DKQConstant.PROCEED_END);
//                            activityDao.save(act);
//                        }
//                    } catch (ParseException e)
//                    {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        }

        SimpleDateFormat DefaultTimeFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Page<Activity> data = findNotEnd(1);
        if(null != data && null != data.getContent() && data.getContent().size()>0)
        {
            for(Activity act:data.getContent())
            {
                if(act.getStatus() == DKQConstant.PROCEED_NOT_START)
                {
                    try
                    {
                        Date today = new Date();
                        Date actStartDate = DefaultTimeFormatter.parse(act.getStartTime());
                        //检查当前活动是否开始
                        if(today.after(actStartDate))
                        {
                            act.setStatus(DKQConstant.PROCEED_START);
                            activityDao.save(act);
                        }
                    } catch (ParseException e)
                    {
                        e.printStackTrace();
                    }
                }
                else if(act.getStatus() == DKQConstant.PROCEED_START)
                {
                    try
                    {
                        Date today = new Date();
                        Date actEndDate = DefaultTimeFormatter.parse(act.getEndTime());
                        //检查当前活动是否已结束
                        if(today.after(actEndDate))
                        {
                            act.setStatus(DKQConstant.PROCEED_END);
                            activityDao.save(act);
                        }
                    } catch (ParseException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        }

        //signInfo();
    }

    @Override
    public void signInfo() throws ServiceRuntimeException
    {
        SimpleDateFormat DefaultTimeFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        //查询当天所有未开始的活动
        List<Activity> unStarts = this.findToday(DateUtil.convertDefaultDateString(new Date()),DKQConstant.PROCEED_NOT_START);
        for(Activity act:unStarts)
        {
            try
            {
                Date today = new Date();
                Date actStartDate = DefaultTimeFormatter.parse(act.getStartTime());
                //计算距离活动开始还有多长时间
                long times = DateUtil.countMinutes(today,actStartDate);
                //System.out.println("signInfo--"+act.getId()+"---in------->"+times);
                if(times==5)
                {
                    PushActivityMesssage.getInstance().startSignIn(baseDAO,act.getId(),act.getName(),act.getActivityCode());
                }
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        //查询当天所有已结束的活动
        List<Activity> ends = this.findToday(DateUtil.convertDefaultDateString(new Date()),DKQConstant.PROCEED_END);
        for(Activity act:ends)
        {
            try
            {
                if(act.getLocked() == DKQConstant.ACTIVITY_LOCK)
                    continue;
                Date today = new Date();
                Date actEndDate = DefaultTimeFormatter.parse(act.getEndTime());
                //计算距离活动开始还有多长时间
                long times = DateUtil.countMinutes(actEndDate,today);
                //System.out.println("signInfo--"+act.getId()+"---out------->"+times);
                if(times==5)
                {
                    PushActivityMesssage.getInstance().startSignOut(baseDAO,act.getId(), act.getName(),act.getActivityCode());
                }
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }


    }

    /**
     * 创建分页请求.
     */
    private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
        Sort sort = null;
        if ("auto".equals(sortType)) {
            sort = new Sort(Sort.Direction.DESC, "id");
        } else if ("CREATE_TIME".equals(sortType)) {
            sort = new Sort(Sort.Direction.ASC, "title");
        }

        return new PageRequest(pageNumber - 1, pagzSize, sort);
    }

    /**
     * 创建动态查询条件组合.
     */
    private Specification<Task> buildSpecification(Long groupId, Map<String, Object> searchParams) {
        Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
        filters.put("group.id", new SearchFilter("group.id", SearchFilter.Operator.EQ, groupId));
        Specification<Task> spec = DynamicSpecifications.bySearchFilter(filters.values(), Task.class);
        return spec;
    }

    //志愿者一号通：所在团体的省编号（2位）+所在省人数排序编号（8位，剩下的补0）+随机数（1位）

    //志愿团体一号通：所在团组织机构代码（后9位）+排序号（3位）

    //活动一号通：1.体制内团体的活动—发布活动的团体所在团组织的省份（2位）+创建时间年份（4位）+排序号（7位）2.社会团体—发布活动的团体所在的省份（2位）+创建时间年份（4位）+排序号（7位）


    //    活动一号通：  1.体制内团体的活动—发布活动的团体所在团组织的省份（2位）+创建时间年份（4位）+排序号（7位）
    //                2.社会团体—发布活动的团体所在的省份（2位）+创建时间年份（4位）+排序号（7位）
    private String createActivityCode(String province,String city,String district)
    {
        StringBuffer sb = new StringBuffer();
        if(StringUtils.isBlank(province))
            province = "江苏省";

        String code = activityDao.queryProvinceCode(province);
        sb.append("A");
        sb.append(code);
        sb.append(DateUtil.currentDateStringTrim());
        String targetStr[] = Identities.uuid().split("-");
        sb.append(targetStr[1].toUpperCase());
        return sb.toString();
    }
    private String createActivityCodeForDate(String province,String date)
    {
        StringBuffer sb = new StringBuffer();
        if(StringUtils.isBlank(province))
            province = "江苏省";

        String code = activityDao.queryProvinceCode(province);
        sb.append("A");
        sb.append(code);
        sb.append(date);
        String targetStr[] = Identities.uuid().split("-");
        sb.append(targetStr[1].toUpperCase());
        return sb.toString();
    }
    private String createQr(String activityCode)
    {
        //return Img2Base64Util.getImgStr(Img2Base64Util.createQRImage("activity", activityCode));
        ByteArrayOutputStream out =  QRCode.from(activityCode).to(ImageType.PNG).stream();
        byte[] data = out.toByteArray();
        String qr = new String(Base64.encodeBase64(data));
        //System.out.println(qr);
        return qr;
    }

    @Override
    public int countByStatus(int status) throws ServiceRuntimeException
    {
        return activityDao.countByStatus(status);
    }

    @Override
    public int countByGroupAndStatus(long groupId, int status) throws ServiceRuntimeException
    {
        return activityDao.countByGroupAndStatus(groupId,status);
    }

    @Override
    public List<Activity> findNameLike(String content) throws ServiceRuntimeException
    {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = new PageRequest(0, 10, sort);

        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("delStatus", new SearchFilter("delStatus", SearchFilter.Operator.EQ, DKQConstant.DEL_NO));
        filters.put("name", new SearchFilter("name", SearchFilter.Operator.LIKE, content.trim()));
        Specification<Activity> spec = DynamicSpecifications.bySearchFilter(filters.values(), Activity.class);
        Page<Activity> data =  this.activityDao.findAll(spec, pageRequest);
        if(null == data || data.getContent() == null || data.getContent().size() ==0)
            return null;
        return data.getContent();
    }

    @Override
    public List<Activity> findTagsLike(String tag) throws ServiceRuntimeException
    {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = new PageRequest(0, 10, sort);

        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("delStatus", new SearchFilter("delStatus", SearchFilter.Operator.EQ, DKQConstant.DEL_NO));
        filters.put("tags", new SearchFilter("tags", SearchFilter.Operator.LIKE, tag.trim()));
        Specification<Activity> spec = DynamicSpecifications.bySearchFilter(filters.values(), Activity.class);
        Page<Activity> data =  this.activityDao.findAll(spec, pageRequest);
        if(null == data || data.getContent() == null || data.getContent().size() ==0)
            return null;
        return data.getContent();
    }

    @Override
    public Page<Activity> searchActivity(String groupCode, String title, String startDate, String endDate, int pageNumber) throws ServiceRuntimeException
    {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = new PageRequest(0, 50, sort);

        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("group.groupCode", new SearchFilter("group.groupCode", SearchFilter.Operator.EQ, groupCode));

        if(StringUtils.isNotBlank(title))
        {
            filters.put("name", new SearchFilter("name", SearchFilter.Operator.LIKE, title.trim()));
        }
        if(StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate))
        {
            filters.put("startTime", new SearchFilter("startTime", SearchFilter.Operator.GTE, startDate));
            filters.put("endTime", new SearchFilter("endTime", SearchFilter.Operator.LTE, endDate));
        }
        filters.put("delStatus", new SearchFilter("delStatus", SearchFilter.Operator.EQ, DKQConstant.DEL_NO));
        Specification<Activity> spec = DynamicSpecifications.bySearchFilter(filters.values(), Activity.class);
        return this.activityDao.findAll(spec, pageRequest);
    }
}
